<?
	class User_model extends CI_Model
	{
		private $userId = 0;
		
		function __construct()
		{
			parent::__construct();
			session_start();

			if (!empty($_SESSION['browserSecData']))
			{
				if ($_SESSION['browserSecData'] != browserSecData())
				{
					session_destroy();
					session_start();
				}
			}
			
			if (empty($_SESSION['hashId'])) $_SESSION['hashId'] = random_string('alnum', 32);
			if (!empty($_SESSION['userId'])) $this->userId = $_SESSION['userId'];
		}
		
		public function id()
		{
			return abs(@abs($this->userId));
		}
		
		
		public function data($field = false)
		{
			if (empty($_SESSION['userData']) || !is_object($_SESSION['userData'])) return false;
			
			if (!empty($field))
			{
				if (!empty($_SESSION['userData']->$field))	return $_SESSION['userData']->$field;
				return false;
			}

			return $_SESSION['userData'];
		}
		

		/* авторизация через пост */
		public function auth()
		{
			$email = $this->input->post('pEmail');
			$postHash = $this->input->post('password');
			$recoveryForm = $this->load->view('user/passwordRecoveryForm', array(), true);
			
			if (empty($email) || empty($postHash) || empty($_SESSION['hashId'])) return 'Не указан логин или пароль'.$recoveryForm;
			
			$res = $this->db->where(array('pEmail' => $email, 'dActivated >' => 0, 'dDeleted' => 0))->get('user')->result();
			// die($this->db->last_query());
			if (empty($res[0]->id)) return 'Неверный логин или пароль '.$recoveryForm;
			
			$user = $res[0];

			$sessHash = myMD5($email . $user->pPass . $_SESSION['hashId']);

			
			if ($postHash == $sessHash)
			{			
				$this->userId = $user->id;
				$_SESSION['userId'] = $user->id;
				$_SESSION['hash'] = $postHash;
				$_SESSION['browserSecData'] = browserSecData();
				$_SESSION['userData'] = $user;
				return true;
			} else return 'Неверный логин или пароль.'.$recoveryForm;
		}
		
		public function check($email)
		{
			$this->db->from('user');
			$this->db->where('pEmail', $email);
			return $this->db->count_all_results();
		}
		
		public function logout()
		{
			session_destroy();
			if (!empty($_SERVER['HTTP_REFERER'])) header('location: '.$_SERVER['HTTP_REFERER']);
			header('Location: '.$_SERVER['HTTP_REFERER']);
		}		

		public function prepareUserData($data, $update = false)
		{
			$data = (object)$data;
			$error = array();
			
			if (empty($data->pName) || mb_strlen($data->pName) < 2)
				$error[] = 'Имя должно быть не короче двух символов.';	else
					$data->pName = htmlspecialchars($data->pName);
			
			if (empty($data->pFamily) || mb_strlen($data->pFamily) < 2)
				$error[] = 'Фамилия должна быть не короче двух символов.'; else
					$data->pFamily = htmlspecialchars($data->pFamily);				
			
			
			if (!$update)
				if (empty($data->pEmail) || !isValidEmail($data->pEmail)) $error[] = 'Неверный формат email.';
			
			if (empty( $data->tCity))
				$data->tCity = 1;

			if (!$update && empty($data->pPass)) $error[] = 'Неивестная ошибка в пароле.';

			
			if (!sizeof($error))
			{
				$insDt = new stdClass();
				$insDt->pName			= $data->pName;
				$insDt->pFamily			= $data->pFamily;
				$insDt->pAdress			= $data->pAdress;
				$insDt->pPhone			= $data->pPhone;
				$insDt->tCity			= $data->tCity;

				if ($update) return $insDt;

				if (!$update)
				{
					if (!$this->check($data->pEmail))
					{
						$insDt->pEmail			= $data->pEmail;
						$insDt->pPass			= $data->pPass;
						$insDt->dCreate			= now();
						$insDt->dActivated		= 0;
						$insDt->dDeleted		= 0;
						$insDt->pActCode		= random_string('alnum', 32);
						$insDt->tAccType 		= 0;
 						return $insDt;
					} else $error[] = 'Пользователь с таким email уже существует.';
				}
			}
			return $error;
		}
		
		public function add($data, $hashPass = false)
		{
			$error = array();
			$insDt = $this->prepareUserData($data);
						
			if (is_object($insDt))
			{
				$insDt->pPass = myMD5(mb_strtolower(trim($insDt->pEmail)).trim($insDt->pPass));

				$this->db->insert('user', $insDt);
				$uid = $this->db->insert_id();
				
				if ($uid)
				{
					$emailText = $this->load->view('user/mailActivation', array('pActCode' => $insDt->pActCode), true);

					if (!sendMail($insDt->pEmail, $emailText))
						$error[] = 'Ошибка при отправке Email';
				
					return $uid;
				} else $error[] = 'Ошибка при выполнении запроса.';	
			}
			if (is_array($insDt))
				$error = $insDt;
			return $error;
		}

		public function getUser($userId)
		{
			if (!$userId)
				return "Такого пользователя не существует или id задан неверно";
			$userId = abs(@abs($userId));

			$this->db->from('user');
			$this->db->where('id', $userId);
			$res = $this->db->get()->result();

			if (is_arr($res)) return $res[0];
			return false;
		}

		public function refreshData()
		{
			if ($this->id())
			{
				$res = $this->db->where(array('id' => $this->id(), 'dActivated >' => 0, 'dDeleted' => 0))->get('user')->result();
				$user = $res[0];
				$_SESSION['userData'] = $user;
			}
		}


		public function update($data)
		{
			if (!empty($data->ava))
			{
				$this->delAva();
				$uploadImage = uploadImage($data->ava, rootDir().'uploads/users/', rootDir().'uploads/users/thumbs/');
				if (!is_arr($uploadImage) && !empty($uploadImage->fileName))
				{
					$data->pImg = $uploadImage->fileName;
				}
			}
			unset($data->ava);

			$this->db->where('id', $this->id());
			$this->db->where('dDeleted', 0);
			$this->db->where('dActivated >', 0);
			$this->db->update('user', $data);
			$this->refreshData();
		}
		
		public function recPass($pEmail)
		{
			$data = new stdClass();
			$data->pPassRecCode = random_string('alnum', 32);
			$data->dPassRecCodeTime = now();
			
			$this->db->where('pEmail', $pEmail);
			$this->db->update('user', $data);
			
			$emailText = $this->load->view('user/passRecoveryTemplate', array('pPassRecCode' => $data->pPassRecCode), true);

			$send = sendMail($pEmail, $emailText);
			if (!$send)
			{
				$error[] = 'Ошибка при отправке Email';
				return 0;
			}
			else 
				return $send;
		}
		
		function checkPassRecoveryCode($pPassRecCode = "", &$pEmail)
		{
			$this->db->from('user');
			$this->db->where('pPassRecCode', $pPassRecCode);
			$data = $this->db->get()->result();
			if (is_array($data) && sizeof($data))
			{
				$data = $data[0];
				if (abs($data->dPassRecCodeTime - now()) > 15*60)
				{				
					$this->db->where('pPassRecCode', $pPassRecCode);
					$this->db->update('user', array('pPassRecCode' => '', 'dPassRecCodeTime' => 0));
					return "Код восстановления пароля устарел.";
				}
				$pEmail = $data->pEmail;
				return true;
			} else return "Код восстановления пароля неверный.";
		}
		
		function updatePass($login, $pass, $hash = false)
		{
			if ($hash) $pass = myMD5($login.$pass);
			
			$this->db->where('pEmail', $login);
			$this->db->update('user', array('pPass' => $pass, 'pPassRecCode' => '', 'dPassRecCodeTime' => 0));
		}
		
		public function activate($code)
		{
			$this->db->where('pActCode', $code);
			$this->db->where('dActivated', 0);
			$this->db->from('user');

			if ($this->db->count_all_results())
			{
				$this->db->where('pActCode', $code);
				$res = $this->db->update('user', array('dActivated' => now()));
				$res = (bool)$res;
				return $res;
			} else return 'Ошибка активации, возможно пользователь уже активирован.';
		}

		function getCities()
		{
			$res = $this->db->get('city')->result();
			$res = setKeys($res, 'id');
			return $res;
		}


	}